from System import *
from System.Windows import *
from System.Windows.Threading import *
from System.Windows.Media import *
from System import *
from System.Net import *
from System.Text import *
from System.Collections import *
from System.Collections.Specialized import *
from System.Windows.Media.Imaging import *
from System.Diagnostics import *

from System.Text.RegularExpressions import *

URLS = {
		"auth" : "http://twitter.com/account/verify_credentials.json",
		"friends" : "http://twitter.com/statuses/friends_timeline.json",
		"update" : "http://twitter.com/statuses/update.json",
		"search" : "http://search.twitter.com/search.json"
}

tweets = [{"name":"Gestalt", "image_url":"http://assets0.twitter.com/images/twitter.png", "text":"loading tweets. Click buttons to read more!", "created_at":DateTime.Now.ToShortDateString(), "source":"gestalt"}]
current_tweet = -1
qs = None

class Twitter:
	""" I deal with talking to Twitter. """
	def __init__(self):
	    self.hash = ""
	    self.presenters = []

	def credentials(username, password):
	    utf8 = UTF8Encoding();
	    self.hash = Convert.ToBase64String(utf8.GetBytes("%s:%s" % (username,password)))

	def add_presenter(self, presenter_instance):
	    self.presenters.append(presenter_instance)

	def friends_timeline(self):
		""" I get your friends' update """
		url = "%s" % URLS["friends"]
		self.fetch(url)

	def update(self, msg):
		""" I make updates for you. """
		url = "%s?status=%s" % (URLS["update"], msg)
		self.fetch(url, "POST")

	def search(self, query_terms, query_string=None):
	    """ Search for anything you want. I'll find it. You choose how to use the results. """
	    url = URLS["search"]
	    if(query_string):
	        url += query_string
	    else:
	        url += "?q=" + query_terms
	    self.fetch(url)

	def update_status_list(self, sender, args):
	    x = 0
		#if (args.Error == None):
		#	resp = JsonValue.Parse(args.Result)
		#	for presenter in self.presenters:
		#		presenter.add_to_status_list(resp)
		#else:
		#	log(args.Error)

	def fetch(self, uri, method="GET"):
		client = WebClient()
		
		#online version
		#proxy = str("http://www.visitmix.com/labs/gestalt/samples/twitter.badge/TwitterProxy.ashx?u=%s&m=%s" % (HttpUtility.UrlEncode(uri), HttpUtility.UrlEncode(method)))
		#http://www.visitmix.com/labs/gestalt/samples/twitter.badge/TwitterProxy.ashx?u=http%3a%2f%2fsearch.twitter.com%2fsearch.json%3ftag%3dgestalt&m=GET
		
		#VS version
		proxy = str("http://localhost:54151/samples/twitter.badge/TwitterProxy.ashx?u=%s&m=%s" % (HttpUtility.UrlEncode(uri), HttpUtility.UrlEncode(method)))
		#http://localhost/gestalt/TwitterProxy.ashx?u=http%3a%2f%2fsearch.twitter.com%2fsearch.json%3ftag%3dgestalt&m=GET
		#http://localhost:54151/samples/twitter.badge/TwitterProxy.ashx?u=http%3a%2f%2fsearch.twitter.com%2fsearch.json%3ftag%3dgestalt&m=GET
		
		if(self.hash):
		    proxy += "&ph=%s" % HttpUtility.UrlEncode(self.hash)
		    
		log(proxy)
		
		client.DownloadStringAsync(Uri(proxy))
		
		#client.DownloadStringAsync(Uri(uri)) // works, but will quickly rate limit you ;)
		
		#client.DownloadStringCompleted += self.update_status_list

class BadgePresenter():
    def add_to_status_list(self, json):
        global qs
        qs = json.refresh_url
        for status in json.results:
            tweets.append({"name":status.from_user, "image_url":status.profile_image_url.Replace("\\",""), "text":status.text, "created_at":DateTime.Parse(status.created_at).ToShortDateString(), "source":status.source})
                    
def ping_twitter(sender, args):
    twitter.search("fallenrogue", qs)
    log("called %s" % DateTime.Now.ToString())

def move_next(sender, args):
    go_to_next_tweet(sender, args)

def go_to_next_tweet(sender, args):
    global current_tweet
    if(current_tweet < len(tweets)-1):
        current_tweet += 1
    else:
        current_tweet = -1
    update_ui(tweets[current_tweet])

def go_to_previous_tweet(sender, args):
    global current_tweet
    if(current_tweet >= 1):
        current_tweet -= 1
    else:
        current_tweet = len(tweets)-1
    update_ui(tweets[current_tweet])

def update_ui(data_hash):
    me.badge.fade_out.Begin()
    me.status.Text = Regex.Unescape(data_hash["text"])
    me.details.Text = "from %s on %s from %s" % (data_hash["name"], data_hash["created_at"], data_hash["source"])
    
    imageUrl = data_hash["image_url"]
    
    if (imageUrl.ToString().Contains(".gif")):
		imageUrl = "http://assets0.twitter.com/images/twitter.png"
    
    me.avatar.Source = BitmapImage(Uri(imageUrl))
    #me.username.Text = data_hash["name"]
    me.badge.fade_in.Begin()

def log(msg):
    document.msg.innerHTML = "<p>"+str(msg)+"</p>"
    #Debug.WriteLine(str(msg))
    
twitter = Twitter()
twitter.add_presenter(BadgePresenter())
twitter.search(None, "?tag=gestalt")
go_to_next_tweet(None, None)

ping_timer = DispatcherTimer(Interval = TimeSpan(0, 0, 0, 120, 0))
ping_timer.Tick += ping_twitter
ping_timer.Start()

cross_fader = DispatcherTimer(Interval = TimeSpan(0, 0, 0, 10, 0))
cross_fader.Tick += move_next
cross_fader.Start()

me.next.Click += go_to_next_tweet
me.previous.Click += go_to_previous_tweet